package org.nutils.streams;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Normal {@link InputStream} behavior. Just adds a method to reflect that the
 * end of stream has been reached without disturbing the underlying stream.
 * 
 * @author noah
 * 
 */
public class IsFinishedInputStream extends FilterInputStream {

	private boolean finished;

	public IsFinishedInputStream(InputStream in) {
		super(in);
	}

	@Override
	public int read() throws IOException {
		return check(super.read());
	}

	@Override
	public int read(byte[] b) throws IOException {
		return check(super.read(b));
	}

	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		return check(super.read(b, off, len));
	}

	/**
	 * Checks for end of stream, returning the value passed in.
	 * 
	 * @param read
	 * @return
	 */
	private int check(final int read) {
		if (read == -1) {
			finished = true;
		}
		return read;
	}

	/**
	 * Marks as finished and calls super.close.
	 */
	@Override
	public void close() throws IOException {
		finished = true;
		super.close();
	}

	/**
	 * 
	 * @return true if EOS was reached or close was called.
	 */
	public boolean isFinished() {
		return finished;
	}
}
